package inabit.inabitcompiler.productions.rule.expressions;

import inabit.compiler.parser.grammar.NonTerminal;
import inabit.compiler.parser.grammar.Production;
import inabit.compiler.parser.grammar.Symbol;
import inabit.compiler.parser.grammar.Terminal;
import inabit.data.expression.Expression;
import inabit.data.expression.RelationalExpression;
import inabit.fuzzy.data.FuzzySet;
import inabit.fuzzy.expressions.FuzzyExpression;
import inabit.inabitcompiler.lexical.InabitTokenClass;
import inabit.inabitcompiler.parser.InabitSemanticAction;

/** K -> id O A */
/**@author Rafael Rocha*/
public class K_Rule extends Production {
	private Terminal id;
	private NonTerminal Rest;

	public K_Rule() {
		super("K");
	}

	public Symbol[] production(final NonTerminal nonTerminal) {
		id = new Terminal(InabitTokenClass.ID);
		Rest = new NonTerminal("Rest");
		Symbol[] symbols = { id, Rest, new InabitSemanticAction(nonTerminal) {
			public void execute() throws Exception {
				String[] rightPart = Rest.code.split(":");
				Expression e = null;
				if(rightPart[0].equals("is")) {
					FuzzySet set = getFuzzySet(rightPart[1]);
					if(set == null) {
						throw new Exception("Coudn't find fuzzy set " + rightPart[1]);
					}
					e = new FuzzyExpression(id.getValue(), set);
					
				}else {
					String o = rightPart[0];
					String a = rightPart[1];
					e = new RelationalExpression(id.getValue(),
							Integer.parseInt(o),
							getArithmeticExpression(a));
					
				}
				nonTerminal.code = addExpressionAndGetCode(e);

			}
		} };
		return symbols;
	}
}
